#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
自动修复constants_v2.py中的字段配置
根据MySQL数据库实际结构自动同步字段配置
"""
import sys
import os
import re

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import pymysql
from backend.config.constants_v2 import ALL_FIELD_CONFIG_REGISTRY

def get_mysql_column_type(sql_type):
    """将MySQL SQL类型转换为标准类型"""
    type_str = str(sql_type).upper()
    
    if 'INT' in type_str or 'BIGINT' in type_str or 'SMALLINT' in type_str:
        return 'int'
    elif 'VARCHAR' in type_str:
        return 'string' 
    elif 'TEXT' in type_str or 'LONGTEXT' in type_str or 'MEDIUMTEXT' in type_str:
        return 'text'
    elif 'FLOAT' in type_str or 'DOUBLE' in type_str or 'DECIMAL' in type_str:
        return 'float'
    elif 'BOOLEAN' in type_str or 'TINYINT(1)' in type_str:
        return 'bool'
    elif 'DATE' in type_str and 'TIME' not in type_str:
        return 'date'
    elif 'TIME' in type_str and 'DATE' not in type_str:
        return 'time'
    elif 'DATETIME' in type_str or 'TIMESTAMP' in type_str:
        return 'datetime'
    elif 'JSON' in type_str:
        return 'json'
    elif 'ENUM' in type_str:
        return 'string'
    else:
        return 'string'  # 默认为string


def get_mysql_schema():
    """获取MySQL数据库的完整结构"""
    connection = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='dev01',
        password='123456',
        database='vision_health',
        charset='utf8mb4'
    )
    
    schema = {}
    cursor = connection.cursor()
    
    # 获取所有表名
    cursor.execute("SHOW TABLES")
    all_tables = [table[0] for table in cursor.fetchall()]
    
    for table_name in all_tables:
        # 获取表结构
        cursor.execute(f"DESCRIBE {table_name}")
        mysql_columns = cursor.fetchall()
        
        # 解析字段信息
        table_fields = {}
        for col_info in mysql_columns:
            field_name = col_info[0]
            mysql_type = col_info[1]
            standard_type = get_mysql_column_type(mysql_type)
            table_fields[field_name] = {
                'type': standard_type,
                'mysql_type': mysql_type,
                'nullable': col_info[2] == 'YES',
                'key': col_info[3],
                'default': col_info[4],
                'extra': col_info[5]
            }
        
        schema[table_name] = table_fields
    
    cursor.close()
    connection.close()
    
    return schema


def generate_fixed_config():
    """生成修复后的配置"""
    mysql_schema = get_mysql_schema()
    
    # 生成新的配置
    new_config = {}
    
    # 处理所有MySQL表
    for table_name, mysql_fields in mysql_schema.items():
        table_config = {}
        
        for field_name, field_info in mysql_fields.items():
            field_config = {
                "type": field_info['type'],
                "display_name": field_name
            }
            
            # 添加一些常用的显示名称映射
            display_name_map = {
                'id': f'{table_name[:-1] if table_name.endswith("s") else table_name}ID',
                'created_at': '创建时间',
                'updated_at': '更新时间',
                'name': '名称',
                'title': '标题',
                'content': '内容',
                'description': '描述',
                'status': '状态',
                'user_id': '用户ID',
                'student_id': '学生ID'
            }
            
            if field_name in display_name_map:
                field_config["display_name"] = display_name_map[field_name]
            
            table_config[field_name] = field_config
        
        new_config[table_name] = table_config
    
    return new_config


def generate_config_file_content(new_config):
    """生成配置文件内容"""
    lines = []
    lines.append('# 根据MySQL数据库实际结构自动生成的字段配置')
    lines.append('# 此配置确保与数据库结构完全一致')
    lines.append('')
    lines.append('ALL_FIELD_CONFIG_REGISTRY = {')
    
    for table_name, table_config in sorted(new_config.items()):
        lines.append(f'    "{table_name}": {{')
        
        for field_name, field_config in sorted(table_config.items()):
            type_str = field_config['type']
            display_name = field_config['display_name']
            lines.append(f'        "{field_name}": {{"type": "{type_str}", "display_name": "{display_name}"}},')
        
        lines.append('    },')
        lines.append('')
    
    lines.append('}')
    
    return '\n'.join(lines)


def main():
    """主函数"""
    print("🔄 开始自动修复constants_v2.py配置...")
    
    try:
        # 获取新配置
        new_config = generate_fixed_config()
        
        # 生成配置文件内容
        config_content = generate_config_file_content(new_config)
        
        # 写入到新文件
        output_file = 'constants_v2_fixed.py'
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(config_content)
        
        print(f"✅ 修复完成！新配置已保存到 {output_file}")
        print(f"📊 共处理 {len(new_config)} 个表")
        
        # 统计字段数量
        total_fields = sum(len(table_config) for table_config in new_config.values())
        print(f"📋 共处理 {total_fields} 个字段")
        
        print("\n⚠️  请手动检查生成的配置文件，确认无误后替换原文件")
        
    except Exception as e:
        print(f"❌ 修复失败: {e}")
        return False
    
    return True


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
